<template>
  <div id="docSubmitOrder">
    <div class='mc' v-show="isShowToast" @click.stop="goOrder">
      <div>
        <img class="message" src="../../../image/order_success.png" width="100" height="" alt="">
        <img class="close" src="../../../image/closed_inform.png" width="28" height="" alt="" @click.stop="goOrder">
        <div>
          <h3>订单提交成功</h3>
          <p>
            下单成功后10分钟内诊所会及时和你联系确认订单信息,请到门店现场支付款项!
          </p>
          <a @click='lookOrderDetails'>查看订单详情</a>
        </div>
      </div>
    </div>
    <header>
      <i @click="goBack()"></i>
      <div>购物车（不要了）</div>
      <span @click='manageCart()'>{{manage}}</span>
    </header>
    <div class="sc-goods-list">
      <div class="sc-goods-list-one" v-for='(item,index) in list' :key="index">
        <label class="sc-goods-label" @change="select">
          <input type="checkbox" class="sc-goods-checkbox" v-model="gender" :value="item" />
          <span class="sc-normal"></span>
          <div class="sc-goods-cover">
            <img :src="item.img_url" />
          </div>
          <div class="sc-goods-name">
            {{item.name}}
          </div>
          <div class="sc-goods-price-number">
            <span class="sc-goods-price">{{item.price}}</span>
            <span class="sc-goods-number">×{{item.num}}</span>
          </div>
        </label>
      </div>
      <div v-show="type">
        <div class="sc-goods-list-one last" style="height:0.5rem;line-height: 0.5rem">
          <label class="sc-goods-label">
            <input type="checkbox" class="sc-goods-checkbox" checked disabled/>
            <span class="sc-normal" style="margin-top:17px"></span>
            <span style="margin-left:15px">技术指导费</span>
            <span style="color:#e5322d">￥200</span>
          </label>
        </div>
      </div>

      <div class="sc-goods-list-one last" style="height:0.5rem;line-height: 0.5rem">
        <label class="sc-goods-label">
          <input type="checkbox" class="sc-goods-checkbox" checked disabled/>
          <span class="sc-normal" style="margin-top:17px"></span>
          <span style="margin-left:15px">就诊时段价钱</span>
          <span style="color:#e5322d">￥{{price}}</span>
        </label>
      </div>
    </div>
    <div class="back">
      <router-link to="home">
        回到首页
      </router-link>
    </div>
    <div class="sc-foot-gotopayfor">
      <div class="sc-foot-left">
        <div @click="checkedall()">
          <span class="sc-all-normal" v-show="!isSelectAll"></span>
          <span class="sc-all-normal allchecked" v-show="isSelectAll"></span>
          <span class="sc-all-normal-title">全选</span>
        </div>
        <span class="sc-zongjia">{{totalPrice}}</span>
        <span class="sc-zongjia-title">合计:</span>
      </div>
      <div class="sc-foot-right" @click="balance">{{status}}</div>
    </div>

  </div>
</template>
<script>
  import {
    MessageBox
  } from 'mint-ui';
  export default {
    data() {
      return {
        id: '',
        bldoctorname: '',
        price: '0',
        isShowMc: false, //下单成功弹窗
        list: [],
        checked: 0,
        gender: [], //选择的商品
        isSelectAll: false,
        totalPrice: 0,
        guide: 0,
        status: '结算', //确认下单||删除
        manage: '管理', //管理or取消
        isShowToast: false, //确认下单后提示
        type_sub: '',
        type: false,
        infoObj: [],
        obj: {
          infoObj: '', //患者的病历
          doctorid: localStorage.getItem("loginMobile"),
          clinicid: '',
          docinfo: '',
          gids: '',
          total_price: '',
        },
        old_orderid: '',
      }
    },
    created() {
      this.init();
      this.getCartsData();
    },
    methods: {
      // 获取用户下单信息
      init() {
        this.type_sub = localStorage.getItem("type_sub");
        if (this.type_sub == '"doctor0"') {
          if (this.$route.query.docOrderId) {
            this.type = false
          } else {
            this.type = true
            this.guide = 0;
          }
        } else {
          this.type = false
          this.guide = 0;
        }
        if (this.$route.query.docinfo == undefined) {} else {
          this.price = JSON.parse(this.$route.query.docinfo).price1;
        }
        this.obj.docinfo = this.$route.query.docinfo;
        this.obj.clinicid = this.$route.query.clinicid;
        this.old_orderid = this.$route.query.docOrderId;
        this.getOld_Order();
      },
      goBack() {
        this.$router.back();
      },
      getOld_Order() {
        this.$api.get(this.$api.baseURLSchool, "select_cid/view_doctor_order_clinic/" + this.old_orderid, {}, r => {
          // console.log(r);
          if (r.data.ret == 1) {
            this.obj.old_order_num = r.data.info.order_num;
            this.obj.clinicid = r.data.info.clinicid;
            // console.log(this.obj);
          }
        }, err => {
          console.log(err);
        })
      },
      //获取购物车列表
      getCartsData() {
        this.obj.doctorid = localStorage.getItem("loginMobile");
        // 第一个参数是root--baseurl
        this.$api.get(this.$api.baseURLSchool, "selectdata2/view_goods_tools_cart?uid=" + this.obj.doctorid, {}, r => {
          console.log('***/', r);
          if (r.data.ret == 1) {
            this.list = r.data.info;
          }
        }, err => {
          console.log(err);
        })
      },
      //管理购物车商品
      manageCart() {
        if (this.status == '结算') {
          this.status = '删除';
          this.manage = '取消';
        } else {
          this.status = '结算';
          this.manage = '管理';
        }
      },
      //全选
      checkedall: function () {
        if (!this.isSelectAll) { //全选
          this.gender = [];
          this.totalPrice = 0;
          this.list.forEach((item, index) => {
            this.gender.push(item);
            this.totalPrice += (item.price * item.num);
          });
          this.totalPrice = this.totalPrice + Number(this.price)
          this.isSelectAll = true;
        } else { //反选
          this.gender = [];
          this.totalPrice = 0;
          this.isSelectAll = false;
        }
      },
      //多选框change事件
      select() {
        this.totalPrice = 0;
        this.gender.forEach((item, index) => {
          this.totalPrice += (item.price * item.num);
        });

        this.totalPrice = this.totalPrice + Number(this.price) + Number(this.guide)
        if (this.gender.length < this.list.length) {
          this.isSelectAll = false;
        } else if (this.gender.length == this.list.length) {
          this.isSelectAll = true;
        }
      },
      // 下单后 点击去掉蒙层后
      goOrder() {
        this.isShowToast = false;
      },
      // 支付宝支付
      goPay(order_num) {
        let data = {
          order_num: order_num,
          subject: this.list[0].name,
          amount: this.totalPrice,
        };
        this.$api.post(this.$api.baseURL2, "/alipay_app", data, r => {
            var params = r.data.data;
            cordova.plugins.alipay.payment(params, function () {
              this.$utils._toast('支付成功');
            }, function (reason) {
              this.$utils._toast(reason);
            });
          }, err => {
            console.log(err);
          }, false, false)
      },
      // 删除购物车中商品
      delGoods(data) {
        data.forEach((item, index) => {
          const params = {
            id: item.cid
          }
          this.$api.post(this.$api.baseURLSchool, "dataupdate/tools_carts/del", params, r => {
            if (r.data.ret == 1) { //删除成功 更新购物车表
              this.getCartsData();
            }
          }, err => {
            console.log(err);
          })
        });
      },
      // 提交订单
      submitOrder(obj) {
        if (this.old_orderid) {
          this.$api.post(this.$api.baseURLSchool, "origin_add_order", obj, r => {
            if (r.data.ret == 1) { //提交订单成功
              //提交后删除购物车
              this.delGoods(this.gender);
              // 去支付
              if (this.$route.query.docOrderId) {
                // this.$router.push({
                //   name: 'docOrder',
                //   query: {
                //     user:'doctor'
                //   }
                // });
                this.$utils._toast('加单完成，详情请前往加单列表查看!');

              } else {
                this.goPay(r.data.order_num);
              }
            }
          }, err => {
            console.log(err);
          })
        } else {
          this.$api.post(this.$api.baseURLSchool, "update_doctor_order/add", obj, r => {
            if (r.data.ret == 1) { //提交订单成功
              //提交后删除购物车
              this.delGoods(this.gender);
              // 去支付
              if (this.$route.query.docOrderId) {
                // this.$router.push({
                //   name: 'docOrder',
                //   query: {
                //     user:'doctor'
                //   }
                // });
                this.$utils._toast('加单完成，详情请前往加单列表查看!');
              } else {
                this.goPay(r.data.order_num);
              }
            }
          }, err => {
            console.log(err);
          })
        }


      },
      //结算or删除购物车
      balance() {
        if (this.status == '结算') {
          this.id = localStorage.getItem('blid');
          this.id = JSON.parse(this.id)
          this.bldoctorname = localStorage.getItem('bldoctorname');
          console.log(this.id)
          if (this.id) {
            this.$api.get(this.$api.baseURLSchool, "select_cid/medical_records/" + this.id, {}, r => {
              if (r.data.ret == 1) {
                  console.log(this.obj)
                if (this.gender.length) {
                  this.obj.infoObj = JSON.stringify(r.data.info);
                  this.obj.gids = JSON.stringify(this.gender);
                  this.obj.total_price = this.totalPrice;
                  this.submitOrder(this.obj);
                } else {
                  this.$utils._toast("请选择商品");
                }
              }
            }, err => {
              console.log(err);
            })
          } else {
              console.log(this.gender)
            if (this.gender.length) {
              this.obj.gids = JSON.stringify(this.gender);
              this.obj.total_price = this.totalPrice;
              this.submitOrder(this.obj);
            } else {
              this.$utils._toast("请选择商品");
            }
          }


        } else {
          if (this.gender.length) {
            console.log(this.gender);
            var that = this;
            MessageBox.confirm('确定删除这' + this.gender.length + '件商品?').then(action => {
              this.gender.forEach(function (item, index) {
                console.log(item.cid);
                const params = {
                  id: item.cid
                }
                that.$api.post(that.$api.baseURLSchool, "dataupdate/tools_carts/del", params, r => {
                  if (r.data.ret == 1) { //删除成功 更新购物车表
                    that.getCartsData();
                  }
                }, err => {
                  console.log(err);
                })
              });
              this.status = '结算';
              this.totalPrice = 0;
              this.gender = [];
            }, r => {
              this.status = '删除';
            });

          } else {
            this.$utils._toast("请选择商品");
          }
        }

      },
      //查看订单详情
      lookOrderDetails() {
        this.$router.push({
          name: 'docOrderDetails',
          query: {}
        });
      }

    }
  }

</script>

<style style="scss" scoped>
.back{
    height: 30px;
    width: 110px;
    line-height: 30px;
    text-align: center;
    /* color: #fff; */
    background: #e5322d;
    border-radius: 5px;
    margin-left: 50%;
    margin-bottom: 5px;
    transform: translateX(-50%);
}

</style>
